<?php
/**
 * 模板、素材、字体价格修改 同步产品价格
 *
 * 模板、素材、字体价格修改 同步产品价格(每天晚上12点同步一次价格，包括素材、模板、字体价格的修改，
 * 每次修改不会立即生效，第二天生效)
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\ModifyResourcePriceRecordsService;

use App\Services\PreferentialService\PreferentialService;
use App\Services\Exceptions\PriceErrorException;
use App\Services\SourcePicService\SourcePicTool;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\FontService\FontService;
use Log;
use DB;

class ModifyResourcePriceRecordsService
{
    /**
     * 插入素材价格修改记录
     */
    public function save_modify_resource_price_record($input){
        if(!isset($input['resource_type']) || !isset($input['resource_id']) || !isset($input['admin_id']) ||
            !isset($input['admin_email']) || !isset($input['modify_price'])){
            return false;
        }
        //当天相同的更新操作
        if($input['resource_type'] != 2){
            $begin_time = strtotime(date('Y-m-d',time()));
            $end_time = $begin_time + 3600*24;
            $record = DB::table('modify_resource_price_records')
                ->where('resource_type',$input['resource_type'])
                ->where('resource_id',$input['resource_id'])
                ->where('state',1)
                ->whereBetween('created_at',[$begin_time,$end_time])
                ->select('modify_resource_price_record_id','modify_price','price')
                ->first();
        }else{
            $begin_time = strtotime(date('Y-m-d',time()));
            $end_time = $begin_time + 3600*24;
            $record = DB::table('modify_resource_price_records')
                ->where('resource_type',$input['resource_type'])
                ->where('resource_id',$input['resource_id'])
                ->where('colour_id',$input['colour_id'])
                ->where('state',1)
                ->whereBetween('created_at',[$begin_time,$end_time])
                ->select('modify_resource_price_record_id','modify_price','price')
                ->first();
        }
        if(empty($record)){
            //判断修改的价格与原价是否相等
            if(isset($input['price']) && $input['modify_price'] == $input['price']){
                return true;
            }
            $input['state'] = 1;
            $input['created_at'] = $input['updated_at'] = time();
            $result = DB::table('modify_resource_price_records')->insert($input);
        }else{
            if(isset($input['price'])){
                unset($input['price']);
            }
            if($input['modify_price'] == $record->price){
                //与最初的价格一样 更新旧记录
                $input['state'] = 2;
            }
            $input['updated_at'] = time();
            $result = DB::table('modify_resource_price_records')
                ->where('modify_resource_price_record_id',$record->modify_resource_price_record_id)
                ->update($input);
        }
        return $result;
    }

    /**
     * 修改产品价格
     */
    public static function modify_product_price(){
        //已修改产品ID组
        //$has_mofify_product_ids = array();
        $modify_resource_price_records = DB::table('modify_resource_price_records')
            ->where('state',1)
            ->select('modify_resource_price_record_id','resource_type','resource_id','colour_id','modify_price')
            ->orderBy('created_at','asc')
            ->get()
            ->toArray();
        foreach($modify_resource_price_records as $record){
            switch($record->resource_type){
                case 1 :
                    $flag = SourcePicTool::updateSourcePicPrice($record->resource_id,$record->modify_price);
                    if($flag){
                        self::modify_source_pics($record);
                    }else{
                        Log::info('素材ID为'.$record->resource_id.'的价格更新失败');
                    }
                    break;
                case 2 :
                    $flag = ProductTempTool::updateProductTempColourPrice($record->resource_id,$record->colour_id,$record->modify_price);
                    if($flag){
                        self::modify_product_temps($record);
                    }else{
                        Log::info('模板ID为'.$record->resource_id.',颜色ID为'.$record->colour_id.'的价格更新失败');
                    }
                    break;
                case 3 :
                    $flag = FontService::updateFontPrice($record->resource_id,$record->modify_price);
                    if($flag){
                        self::modify_fonts($record);
                    }else{
                        Log::info('字体ID为'.$record->resource_id.'的价格更新失败');
                    }
                    break;
            }
        }
    }

    static function getMillisecond() {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }

    /**
     * 素材修改
     * @param $record
     * @return mixed
     */
    public static function modify_source_pics($record){
        $product_ids = DB::table('product_print_materials')
            ->where(array(array('creative_id','=',$record->resource_id),array('type','=',1),array('image_type','=',2),array('state','=',1)))
            ->pluck('product_id')
            ->toArray();
        //$product_ids = array_diff($product_ids,$has_mofify_product_ids);
        Log::info('修改产品价格开始，应修改'.count($product_ids).'件产品');
        $error_product_ids = array();
        $result = self::batch_modify_product_price($product_ids,$error_product_ids);
        $flag = self::update_record($record->modify_resource_price_record_id);
        if(count($result['error_product_ids']) > 0){
            Log::info('-----产品价格修改失败-----');
            Log::info($result['error_product_ids']);
        }
        Log::info('修改产品价格结束，实际修改'.$result['r'].'件产品');
    }

    /**
     * 模板修改
     * @param $record
     * @return mixed
     */
    public static function modify_product_temps($record){
        $product_ids = DB::table('products')
            ->where('product_temp_id',$record->resource_id)
            ->where('colour_id',$record->colour_id)
            ->where('state',1)
            ->pluck('product_id')
            ->toArray();
        //$product_ids = array_diff($product_ids,$has_mofify_product_ids);
        Log::info('修改产品价格开始，应修改'.count($product_ids).'件产品');
        $error_product_ids = array();
        $result = self::batch_modify_product_price($product_ids,$error_product_ids);
        $flag = self::update_record($record->modify_resource_price_record_id);
        if(count($result['error_product_ids']) > 0){
            Log::info('-----产品价格修改失败-----');
            Log::info($result['error_product_ids']);
        }
        Log::info('修改产品价格结束，实际修改'.$result['r'].'件产品');
    }

    /**
     * 字体修改
     * @param $record
     * @return mixed
     */
    public static function modify_fonts($record){
        $product_ids = DB::table('product_print_materials')
            ->where(array(array('font_id','=',$record->resource_id),array('type','=',2),array('state','=',1)))
            ->pluck('product_id')
            ->toArray();
        //$product_ids = array_diff($product_ids,$has_mofify_product_ids);
        Log::info('修改产品价格开始，应修改'.count($product_ids).'件产品');
        $error_product_ids = array();
        $result = self::batch_modify_product_price($product_ids,$error_product_ids);
        $flag = self::update_record($record->modify_resource_price_record_id);
        if(count($result['error_product_ids']) > 0){
            Log::info('-----产品价格修改失败-----');
            Log::info($result['error_product_ids']);
        }
        Log::info('修改产品价格结束，实际修改'.$result['r'].'件产品');
    }

    /**
     * 修改产品价格
     * @param $product_ids
     * @param $error_product_ids
     * @return array
     */
    public static function batch_modify_product_price($product_ids,$error_product_ids){
        //批量修改价格
        $r = 0;
        foreach($product_ids as $product_id){
            try{
                DB::beginTransaction();
                $product = DB::table('products')
                    ->where('product_id',$product_id)
                    ->select('product_id','overflow_price','price','preferential_price','product_temp_id','colour_id')
                    ->first();
                if(!empty($product)){
                    //修改价格
                    $product_prices = self::get_total_price($product);
                    if($product_prices['total_price'] != $product->price
                        || $product_prices['total_preferential_price'] != $product->preferential_price){
                        $flag = DB::table('products')
                            ->where('product_id',$product_id)
                            ->update([
                                'price'=>$product_prices['total_price'],
                                'preferential_price'=>$product_prices['total_preferential_price'],
                                'updated_at'=>time()
                            ]);
                        if($flag == 1){
                            //$has_mofify_product_ids[] = $product_id;
                            $r++;
                        }
                    }
                }
            }catch (\Exception $e){
                DB::rollback();
                Log::info($e);
                $error_product_ids[] = $product_id;
                continue;
            }finally{
                DB::commit();
            }
        }
        return array('r'=>$r,'error_product_ids'=>$error_product_ids);
    }

    /**
     * 更新修改记录
     * @param $modify_resource_price_record_id
     */
    public static function update_record($modify_resource_price_record_id){
        $flag = DB::table('modify_resource_price_records')
            ->where('modify_resource_price_record_id',$modify_resource_price_record_id)
            ->update(['state'=>2,'updated_at'=>time()]);
        return $flag;
    }

    /**
     * 获取总价
     * @param $product
     * @return array
     * @throws PriceErrorException
     */
    public static function get_total_price($product){
        $product_prices = self::get_customize_price($product);
        $total_price = bcadd($product->overflow_price, $product_prices['original_price'], 2);
        $total_preferential_price = bcadd($product->overflow_price, $product_prices['preferential_price'], 2);
        return array('total_price' => $total_price, 'total_preferential_price' => $total_preferential_price);
    }

    /**
     * 获取定制成本价格
     * @param $product
     * @return array|bool
     */
    public static function get_customize_price($product)
    {
        $original_price = 0;
        $preferential_price = 0;
        //模板价格 获取产品模板
        $prices = PreferentialService::getResourcePrice($product->product_temp_id, 2, $product->colour_id);
        if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
            throw new PriceErrorException('ID为' . $product->product_temp_id . '的模板价格异常');
        }
        $original_price = bcadd($original_price, $prices['original_price'], 2);
        $preferential_price = bcadd($preferential_price, $prices['preferential_price'], 2);
        //获取素材价格
        $source_pic_ids = DB::table('product_print_materials')
            ->where(array(array('product_id', '=', $product->product_id), array('type', '=', 1), array('image_type', '=', 2), array('state', '=', 1)))
            ->pluck('creative_id')
            ->toArray();
        $source_pic_ids = array_unique($source_pic_ids);
        foreach ($source_pic_ids as $source_pic_id) {
            $prices = PreferentialService::getResourcePrice($source_pic_id, 1);
            if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                throw new PriceErrorException('ID为' . $source_pic_id . '的素材价格异常');
            }
            $original_price = bcadd($original_price, $prices['original_price'], 2);
            $preferential_price = bcadd($preferential_price, $prices['preferential_price'], 2);
        }
        //计算字体价格
        $font_ids = DB::table('product_print_materials')
            ->where(array(array('product_id', '=', $product->product_id), array('type', '=', 2), array('state', '=', 1)))
            ->pluck('font_id')
            ->toArray();
        $font_ids = array_unique($font_ids);
        foreach ($font_ids as $font_id) {
            $prices = PreferentialService::getResourcePrice($font_id, 3);
            if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                throw new PriceErrorException('ID为' . $font_id . '的字体价格异常');
            }
            $original_price = bcadd($original_price, $prices['original_price'], 2);
            $preferential_price = bcadd($preferential_price, $prices['preferential_price'], 2);
        }
        return array('original_price' => $original_price, 'preferential_price' => $preferential_price);
    }

    /**
     * 判断详情是否有修改价格(拉去产品明细 如果有在修改的记录
     * 就取原始价格 没有就取素材、模板、字体实际价格)
     */
    public static function is_resource_modify_price($resource_id,$colour_id,$resource_type){
        $begin_time = strtotime(date('Y-m-d',time()));
        $end_time = $begin_time + 3600*24;
        if($resource_type == 2){
            //模板修改
            $modify_price = DB::table('modify_resource_price_records')
                ->where('resource_id',$resource_id)
                ->where('colour_id',$colour_id)
                ->where('state',1)
                ->whereBetween('created_at',[$begin_time,$end_time])
                ->select('price','modify_price')
                ->first();
        }else{
            $modify_price = DB::table('modify_resource_price_records')
                ->where('resource_id',$resource_id)
                ->where('state',1)
                ->whereBetween('created_at',[$begin_time,$end_time])
                ->select('price','modify_price')
                ->first();
        }
        return empty($modify_price) ? false : array('price'=>$modify_price->price,'modify_price'=>$modify_price->modify_price);//没有返回false 有返回还未修改的价格
    }

    /**
     * 删除定时修改记录
     * @param $resource_id
     * @param $colour_id
     * @param $resource_type
     * @return array|bool
     */
    public static function delete($resource_id,$colour_id,$resource_type){
        $begin_time = strtotime(date('Y-m-d',time()));
        $end_time = $begin_time + 3600*24;
        if($resource_type == 2){
            //模板修改
            $result = DB::table('modify_resource_price_records')
                ->where('resource_id',$resource_id)
                ->where('colour_id',$colour_id)
                ->where('state',1)
                ->whereBetween('created_at',[$begin_time,$end_time])
                ->update(['state'=>2,'updated_at'=>time()]);
        }else{
            $result = DB::table('modify_resource_price_records')
                ->where('resource_id',$resource_id)
                ->where('state',1)
                ->whereBetween('created_at',[$begin_time,$end_time])
                ->update(['state'=>2,'updated_at'=>time()]);
        }
        return empty($result) ? false : true;//没有返回false 有返回还未修改的价格
    }
}